<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\ProjectShowAction;
use App\Models\DepartmentCategory;
use App\Models\Project;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Tree;
use Dcat\Admin\Widgets\Box;
use Dcat\Admin\Widgets\Form as WidgetForm;
use Illuminate\Http\Request;

class ProjectController extends AdminController
{

    /**
     * 返回项目的治疗时段选项
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getTimeRangeOption(Request $request): \Illuminate\Http\JsonResponse
    {
        $provinceId = $request->get('q');
        $project = Project::query()->where('id', $provinceId)->first();
        if (!$project->time_interval)
            return response()->json([]);

        $list = $project->time_group;
        $result = [];
        foreach ($list as $item) {
            $result[] = [
                'id' => $item,
                'text' => $item,
            ];
        }
        return response()->json($result);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMultipleTimeRangeOption(Request $request): \Illuminate\Http\JsonResponse
    {
        $qId = $request->get('q');
        if (!$qId) {
            return response()->json([]);
        }
        $qId = explode(",", $qId);

        $project = Project::query()
            ->whereIn('id', $qId)
            ->where('is_show', 1)
            ->orderBy("time_interval", "desc")
            ->first();
        if (!$project) return response()->json([]);

        $list = $project->time_group;
        $result = [];
        foreach ($list as $item) {
            $result[] = [
                'id' => $item,
                'text' => $item,
            ];
        }
        return response()->json($result);
    }


    public function index(Content $content)
    {
        return $content
            ->translation($this->translation())
            ->title($this->title())
            ->description($this->description()['index'] ?? trans('admin.list'))
            ->body(function (Row $row) {
                $row->column(7, $this->treeView()->render());

                $row->column(5, $this->boxForm());
            });
    }


    protected function grid()
    {
        return Grid::make(new Project(), function (Grid $grid) {
            $grid->disableCreateButton();
            $grid->disableViewButton();
            $grid->id('ID')->bold()->sortable();
            $grid->title->tree(true); // 开启树状表格功能
            $grid->limit_count
                ->display(function ($val) {
                    if ($this['parent_id'] === 0)
                        return '';
                    if (!($val && $this["project_time"] && $this["time_interval"]))
                        return "&nbsp;<i style='color:#4c60a3'>[未完成配置]</i>";
                    else {
                        return "&nbsp;间隔:{$this["time_interval"]}分钟 &nbsp; 时段预约限制:{$this["limit_count"]}次";
                    }
                });
            $grid->order->orderable();
            $grid->setActionClass(\Dcat\Admin\Grid\Displayers\Actions::class);

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('department_id')->select(DepartmentCategory::selectOptions(null, null, false));

            });
        });
    }

    protected function boxForm()
    {
        $form = new WidgetForm();
        $form->action(admin_url('projects'));

        $options = Project::oneLevelOptions();

        $form->select('parent_id')
            ->options($options)
            ->default(0)
            ->when([0], function ($form) {
                $form->select('department_id')
                    ->options(DepartmentCategory::twoLevelOptions(null,  false));
            });
        $form->text('title')->required();

        $form->width(9, 2);
        return Box::make(trans('admin.new'), $form);
    }

    /**
     * @return \Dcat\Admin\Tree
     */
    protected function treeView()
    {

        return new Tree(new Project(), function (Tree $tree) {
            $tree->disableCreateButton();
            $tree->disableQuickCreateButton();
            $tree->disableEditButton();
            $tree->maxDepth(3);

            $tree->actions(function (Tree\Actions $actions) {
                if ($actions->getRow()->extension) {
                    $actions->disableDelete();
                }

                $actions->prepend(new ProjectShowAction());
            });

            $tree->branch(function ($branch) {
                $config = "";
                if ($branch["parent_id"] && !isset($branch['children'])) {
                    if (!($branch["limit_count"] && $branch["project_time"] && $branch["time_interval"]))
                        $config = "&nbsp;<i style='color:#4c60a3'>[未完成配置]</i>";
                    else {
                        $config = "&nbsp;间隔:{$branch["time_interval"]}分钟 &nbsp; 时段预约限制:{$branch["limit_count"]}次";
                    }
                }

                $payload = "<div style='display:inline-block;'>&nbsp;<strong>{$branch['title']}</strong>&nbsp;{$config}</div>";
                return $payload;
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {

        return Form::make(new Project(), function (Form $form) {
            $form->tools(function (Form\Tools $tools) {
                $tools->disableView();
            });

            $model = $form->model();

            $form->display('id', 'ID');
            $options = Project::oneLevelOptions();

            $form->select('parent_id')
                ->options($options)
                ->default(0)
                ->when([0], function ($form) {
                    $form->select('department_id')
                        ->options(DepartmentCategory::twoLevelOptions(null,  false));
                })
                ->saving(function ($v) {
                    return (int)$v;
                });
            $form->text('title')->required();
            $form->switch('is_show');

            if (!request()->has("_order") && $model["parent_id"] && !$model->childrenRelation->count()) {
                $form->number("limit_count")
                    ->customFormat(function ($val) {
                        return $val ?: 5;
                    })
                    ->default(5)->min(1);
                $form->number("time_interval")
                    ->customFormat(function ($val) {
                        return $val ?: 60;
                    })
                    ->default(60)->min(1);
                $form->number("project_time")
                    ->customFormat(function ($val) {
                        return $val ?: 30;
                    })
                    ->default(30)->min(1);
            }

            $form->hidden('depth');
            $form->display('created_at', trans('admin.created_at'));
            $form->display('updated_at', trans('admin.updated_at'));

            $form->submitted(function (Form $form) {
                if (!request()->has("_order")) {
                    if ($pId = $form->input("parent_id")) {
                        $project = Project::query()->select(['id', 'department_id', 'depth'])->where("id", $pId)->first();
                        $dId = $project?->department_id;
                        if (!$dId)
                            $form->responseValidationMessages("parent_id", "父级项目没有绑定科室");
                        $form->input('department_id', $dId);
                        $form->input('depth', $project->depth + 1);
                    } else {
                        $dId = $form->input("department_id");
                        if (!$dId)
                            $form->responseValidationMessages("department_id", "请选择对应的科室");
                        $form->input('depth', 1);
                    }
                }
            });

        })->saved(function (Form $form, $result) {
            $model = $form->model();
            if ($model->depth === 1) {
                $dId = $model->department_id;
                Project::query()
                    ->where('parent_id', $model->id)
                    ->update([
                        'department_id' => $dId
                    ]);

            }
            $response = $form->response()->location('projects');

            if ($result) {
                return $response->success(__('admin.save_succeeded'));
            }

            return $response->info(__('admin.nothing_updated'));
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Project(), function (Show $show) {
            $show->field('id');
            $show->field('title');
            $show->field('is_show');
            $show->field('parent_id');
            $show->field('order');
            $show->field('limit_count');
            $show->field('time_interval');
            $show->field('project_time');
            $show->field('time_range');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }
}
